package com.example.mydy.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
import com.example.mydy.api.UserApi;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import retrofit2.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.Callback;
import retrofit2.Call;
import retrofit2.converter.gson.GsonConverterFactory;
import java.util.HashMap;
import java.util.Map;

import com.example.mydy.api.ApiClient;
import com.example.mydy.api.UserApi;
import com.example.mydy.app.AppGlobalContext;
import com.example.mydy.model.CommonResponse;
import com.example.mydy.model.RewardTask;
import com.example.mydy.model.Task;
import com.google.gson.GsonBuilder;

public class NetworkUtils {
    private static final String TAG = "NetworkUtils";
    private static final String PREFS_NAME = "NetworkPrefs";
    private static final String KEY_AUTH_TOKEN = "auth_token";
    private static final String KEY_USERNAME = "username";
    private static UserApi userApi;
    private static OkHttpClient client;
    
    // 设置离线模式为false，确保总是使用API调用
    public static final boolean USE_OFFLINE_MODE = false;
    
    // 支持模拟器和实际设备访问（备用URL）
    private static final String BASE_URL_EMULATOR = "http://10.0.2.2:3000/";
    private static final String BASE_URL_DEVICE = "http://106.52.82.133:3000/";
    private static final String BASE_URL_REMOTE = "http://106.52.82.133:3000/";
    
    private static final String DEFAULT_BASE_URL = "http://106.52.82.133:3000/";
    private static String currentBaseUrl = DEFAULT_BASE_URL;
    private static Retrofit retrofit = null;
    private static Retrofit authenticatedRetrofit = null;
    private static String cachedToken = null;
    private static String cachedUsername = null;

    public static void init(Context context) {
        if (client == null) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            client = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .build();
        }

        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(currentBaseUrl)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        loadCachedData(context);
    }

    private static void loadCachedData(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        cachedToken = prefs.getString(KEY_AUTH_TOKEN, null);
        cachedUsername = prefs.getString(KEY_USERNAME, null);
    }

    public static void saveAuthToken(Context context, String token) {
        Log.d(TAG, "保存认证令牌");
        if (token == null || token.isEmpty()) {
            Log.w(TAG, "尝试保存空令牌，操作被忽略");
            return;
        }
        
        // 更新缓存
        cachedToken = token;
        
        // 保存到SharedPreferences
        try {
            SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(KEY_AUTH_TOKEN, token);
            boolean success = editor.commit();
            Log.d(TAG, "令牌保存" + (success ? "成功" : "失败") + ", 令牌长度: " + token.length());
        } catch (Exception e) {
            Log.e(TAG, "保存令牌时出错", e);
        }
    }

    public static void saveUsername(Context context, String username) {
        if (username == null || username.isEmpty()) {
            return;
        }
        
        cachedUsername = username;
        
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        prefs.edit().putString(KEY_USERNAME, username).apply();
    }

    public static String getAuthToken() {
        return cachedToken;
    }

    public static String getUsername() {
        return cachedUsername;
    }

    public static void clearAuthToken(Context context) {
        // 清除存储的授权令牌
        SharedPreferencesManager.setLoggedIn(context, false);
        SharedPreferencesManager.setUsername(context, null);
        SharedPreferencesManager.setNickname(context, null);
        SharedPreferencesManager.setAdmin(context, false);
    }

    public static void clearUsername(Context context) {
        cachedUsername = null;
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        prefs.edit().remove(KEY_USERNAME).apply();
    }

    public static UserApi getUserApi() {
        if (retrofit == null) {
            initRetrofit();
        }
        return retrofit.create(UserApi.class);
    }

    public static boolean isNetworkAvailable(Context context) {
        if (context == null) {
            return false;
        }
        
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        }
        
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }

    public static void post(String path, String jsonBody, Callback<ResponseBody> callback) {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, jsonBody);
        getUserApi().genericPost(path, body).enqueue(callback);
    }

    public static void get(String path, Callback<ResponseBody> callback) {
        getUserApi().genericGet(path).enqueue(callback);
    }

    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    public static void clearRetrofit() {
        Log.d(TAG, "清除Retrofit实例");
        retrofit = null;
        client = null;
    }

    /**
     * 设置服务器地址
     */
    public static void setBaseUrl(String url) {
        if (!url.endsWith("/")) {
            url = url + "/";
        }
        currentBaseUrl = url;
        // 不要清除 Retrofit 实例，而是直接初始化
        initRetrofit();
        Log.d(TAG, "设置新的API地址: " + currentBaseUrl);
    }

    /**
     * 自动选择最佳服务器
     */
    public static void autoSelectServer(Context context) {
        Log.d(TAG, "自动选择最佳服务器URL");
        
        // 直接使用默认服务器地址
        currentBaseUrl = DEFAULT_BASE_URL;
        
        // 确保在设置URL后立即初始化Retrofit
        initRetrofit();
        
        // 尝试在后台验证服务器连接
        new Thread(() -> {
            try {
                checkServerConnection(DEFAULT_BASE_URL);
            } catch (Exception e) {
                Log.e(TAG, "服务器连接检查异常", e);
            }
        }).start();
    }

    /**
     * 初始化Retrofit实例
     */
    public static void initRetrofit() {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        
        client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                .build();
        
        retrofit = new Retrofit.Builder()
                .baseUrl(currentBaseUrl)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        
        Log.d(TAG, "Retrofit初始化成功，使用URL: " + currentBaseUrl);
    }

    public static String getCurrentBaseUrl() {
        return currentBaseUrl;
    }

    public static String getAuthToken(Context context) {
        try {
            // 首先尝试使用缓存的令牌
            if (cachedToken != null && !cachedToken.isEmpty()) {
                Log.d(TAG, "使用缓存中的令牌，长度: " + cachedToken.length());
                return cachedToken;
            }
            
            // 从SharedPreferences获取令牌
            try {
                SharedPreferences prefs = context.getSharedPreferences("MyAppPrefs", Context.MODE_PRIVATE);
                String token = prefs.getString(KEY_AUTH_TOKEN, null);
                
                if (token != null && !token.isEmpty()) {
                    Log.d(TAG, "从SharedPreferences获取令牌成功，长度: " + token.length());
                    // 更新缓存
                    cachedToken = token;
                    return token;
                } else {
                    Log.w(TAG, "从SharedPreferences获取令牌失败，令牌为null或空");
                    return null;
                }
            } catch (Exception e) {
                Log.e(TAG, "获取令牌时出错", e);
                return null;
            }
        } catch (Exception e) {
            Log.e(TAG, "令牌处理时发生异常", e);
            return null;
        }
    }
    
    /**
     * 清除所有Retrofit实例，强制重新创建
     */
    public static boolean validateToken(Context context, String token) {
        // 这里可以添加具体的验证逻辑
        return token != null && !token.isEmpty();
    }

    private static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            Log.d(TAG, "创建新的Retrofit实例");
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .addInterceptor(loggingInterceptor)
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(currentBaseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build();
        }
        return retrofit;
    }
    
    /**
     * 处理令牌过期的响应拦截器
     */
    private static class TokenExpiredInterceptor implements Interceptor {
        private final Context context;
        
        public TokenExpiredInterceptor(Context context) {
            this.context = context;
        }
        
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            okhttp3.Response response = chain.proceed(original);
            
            // 检查是否为未授权响应（401）
            if (response.code() == 401) {
                Log.w(TAG, "令牌已过期或无效，需要重新登录");
                
                // 在UI线程上处理令牌过期
                if (context != null) {
                    new android.os.Handler(context.getMainLooper()).post(() -> {
                        // 清除本地令牌
                        clearAuthToken(context);
                        
                        // 提示用户需要重新登录
                        Toast.makeText(context, "登录已过期，请重新登录", Toast.LENGTH_LONG).show();
                        
                        // 跳转到登录页面的操作需要通过Activity上下文处理
                        Log.e(TAG, "令牌过期，需要重新登录");
                    });
                }
            }
            
            return response;
        }
    }

    public static String getErrorMessage(Throwable t) {
        if (t instanceof IOException) {
            return "网络连接失败，请检查网络设置";
        } else if (t instanceof IllegalStateException) {
            return "服务器响应格式错误";
        } else {
            return "请求失败：" + t.getMessage();
        }
    }

    public static String getResponseErrorMessage(Response<?> response) {
        try {
            if (response.errorBody() != null) {
                String errorBody = response.errorBody().string();
                Log.d(TAG, "原始错误响应: " + errorBody);
                
                try {
                    Gson gson = new Gson();
                    JsonObject jsonObject = gson.fromJson(errorBody, JsonObject.class);
                    if (jsonObject != null && jsonObject.has("message")) {
                        return jsonObject.get("message").getAsString();
                    } else if (jsonObject != null && jsonObject.has("error")) {
                        return jsonObject.get("error").getAsString();
                    }
                } catch (Exception e) {
                    Log.e(TAG, "解析JSON错误: " + e.getMessage());
                    // 如果JSON解析失败，尝试直接返回原始响应
                    return errorBody;
                }
                
                return "未知服务器错误";
            }
            return "请求失败，错误码：" + response.code();
        } catch (IOException e) {
            Log.e(TAG, "处理错误响应异常: " + e.getMessage());
            return "解析错误响应失败";
        }
    }

    public static void showNetworkError(Context context) {
        Toast.makeText(context, "网络连接错误，请检查网络设置", Toast.LENGTH_SHORT).show();
    }

    public static Retrofit getAuthenticatedRetrofitInstance(Context context) {
        String token = getAuthToken(context);
        
        if (authenticatedRetrofit != null) {
            return authenticatedRetrofit;
        }
        
        Log.d(TAG, "创建新的认证Retrofit实例, 令牌: " + (token != null ? "存在" : "不存在"));
        
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        Interceptor authInterceptor = chain -> {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder();
            
            if (token != null && !token.isEmpty()) {
                requestBuilder.header("Authorization", "Bearer " + token);
                Log.d(TAG, "添加认证令牌到请求头");
            } else {
                Log.w(TAG, "未添加认证令牌，令牌为空");
            }
            
            Request request = requestBuilder.build();
            return chain.proceed(request);
        };

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(loggingInterceptor)
                .addInterceptor(authInterceptor)
                .addInterceptor(new TokenExpiredInterceptor(context))
                .build();

        authenticatedRetrofit = new Retrofit.Builder()
                .baseUrl(currentBaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
                
        return authenticatedRetrofit;
    }

    /**
     * 获取带认证功能的UserApi实例
     */
    public static UserApi getAuthenticatedUserApi(Context context) {
        // 修改为实际服务器IP和端口
        String BASE_URL = currentBaseUrl; // 使用当前设置的服务器地址
        
        Log.d(TAG, "获取已认证的UserApi");
        
        // 确保令牌设置正确
        final String token = getAuthToken(context);
        Log.d(TAG, "令牌状态: " + (token != null && !token.isEmpty() ? "有效" : "无效"));
        
        // 避免重复创建日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        
        // 创建带认证拦截器的OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(chain -> {
                    Request original = chain.request();
                    Request.Builder builder = original.newBuilder();
                    
                    // 获取最新的令牌
                    String currentToken = getAuthToken(context);
                    
                    // 只有当令牌可用时才添加
                    if (currentToken != null && !currentToken.isEmpty()) {
                        builder.header("Authorization", "Bearer " + currentToken);
                        Log.d(TAG, "添加令牌到请求头");
                    } else {
                        Log.w(TAG, "令牌为空，请求未添加认证头");
                    }
                    
                    Request request = builder.build();
                    return chain.proceed(request);
                })
                .addInterceptor(loggingInterceptor)
                .build();
        
        // 创建Retrofit实例
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
                
        return retrofit.create(UserApi.class);
    }

    public static <T> T getApiService(Class<T> serviceClass) {
        return getRetrofitInstance().create(serviceClass);
    }

    public static <T> T getAuthenticatedApiService(Context context, Class<T> serviceClass) {
        return getAuthenticatedRetrofitInstance(context).create(serviceClass);
    }

    /**
     * 检查服务器连接
     */
    private static void checkServerConnection(String url) {
        try {
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .build();
            
            Request request = new Request.Builder()
                    .url(url + "api/status")
                    .build();
            
            okhttp3.Response response = client.newCall(request).execute();
            boolean isSuccessful = response.isSuccessful();
            response.close();
            
            Log.d(TAG, "服务器连接检查 " + url + ": " + (isSuccessful ? "成功" : "失败"));
        } catch (Exception e) {
            Log.e(TAG, "URL测试失败: " + url, e);
        }
    }

    /**
     * 检查是否为WIFI连接
     */
    public static boolean isWifiConnection(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
    }

    /**
     * 添加悬赏任务 - 通过API
     */
    public static boolean addRewardTask(RewardTask task) {
        // 这是一个模拟的实现
        Log.d(TAG, "添加悬赏任务: " + task.getTitle());
        
        try {
            // 获取当前上下文，因为是静态方法，需要在调用时传入上下文
            Context context = task.getContext();
            if (context == null) {
                Log.e(TAG, "添加悬赏任务失败: 上下文为空");
                return false;
            }
            
            String token = getAuthToken(context);
            if (token == null || token.isEmpty()) {
                Log.e(TAG, "添加悬赏任务失败: 授权令牌为空");
                return false;
            }
            
            // 准备请求数据
            Map<String, Object> taskData = new HashMap<>();
            taskData.put("title", task.getTitle());
            taskData.put("description", task.getDescription());
            taskData.put("reward", task.getReward());
            taskData.put("deadline", task.getDeadline());
            taskData.put("remainingOrders", task.getRemainingOrders());
            
            if (task.getImageUrl() != null && !task.getImageUrl().isEmpty()) {
                taskData.put("imageUrl", task.getImageUrl());
            }
            
            // 获取API实例并发起异步请求
            UserApi api = getAuthenticatedUserApi(context);
            final boolean[] success = {false}; // 用数组存储结果，以便在回调中修改
            final boolean[] completed = {false}; // 用于标记请求是否完成
            
            // 使用API调用发布悬赏任务
            api.publishReward("Bearer " + token, taskData).enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        success[0] = response.body().isSuccess();
                    } else {
                        Log.e(TAG, "添加悬赏任务API调用失败: " + response.code());
                    }
                    completed[0] = true;
                    synchronized (completed) {
                        completed.notify(); // 通知等待线程
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    Log.e(TAG, "添加悬赏任务网络请求失败", t);
                    completed[0] = true;
                    synchronized (completed) {
                        completed.notify(); // 通知等待线程
                    }
                }
            });
            
            // 等待一段时间，最多3秒
            synchronized (completed) {
                if (!completed[0]) {
                    try {
                        completed.wait(3000);
                    } catch (InterruptedException e) {
                        Log.e(TAG, "等待添加悬赏任务结果被中断", e);
                    }
                }
            }
            
            return success[0]; // 返回API调用的实际结果
        } catch (Exception e) {
            Log.e(TAG, "添加悬赏任务失败", e);
            return false;
        }
    }

    /**
     * 更新悬赏任务 - 通过API
     */
    public static boolean updateRewardTask(RewardTask task) {
        Log.d(TAG, "更新悬赏任务: " + task.getId() + ", " + task.getTitle());
        
        try {
            // 获取当前上下文，因为是静态方法，需要在调用时传入上下文
            Context context = task.getContext();
            if (context == null) {
                Log.e(TAG, "更新悬赏任务失败: 上下文为空");
                return false;
            }
            
            String token = getAuthToken(context);
            if (token == null || token.isEmpty()) {
                Log.e(TAG, "更新悬赏任务失败: 授权令牌为空");
                return false;
            }
            
            // 准备请求数据
            Map<String, Object> updateData = new HashMap<>();
            updateData.put("taskId", task.getId());
            updateData.put("progressStatus", task.getProgressStatus());
            updateData.put("reviewTime", task.getReviewTime());
            if (task.getReviewComment() != null && !task.getReviewComment().isEmpty()) {
                updateData.put("reviewComment", task.getReviewComment());
            }
            
            // 获取API实例并发起异步请求
            UserApi api = getAuthenticatedUserApi(context);
            final boolean[] success = {false}; // 用数组存储结果，以便在回调中修改
            final boolean[] completed = {false}; // 用于标记请求是否完成
            
            // 使用API调用，假设有一个API方法updateRewardTask
            api.updateRewardTask("Bearer " + token, task.getId(), updateData).enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        success[0] = response.body().isSuccess();
                    } else {
                        Log.e(TAG, "更新悬赏任务API调用失败: " + response.code());
                    }
                    completed[0] = true;
                    synchronized (completed) {
                        completed.notify(); // 通知等待线程
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    Log.e(TAG, "更新悬赏任务网络请求失败", t);
                    completed[0] = true;
                    synchronized (completed) {
                        completed.notify(); // 通知等待线程
                    }
                }
            });
            
            // 等待一段时间，最多3秒
            synchronized (completed) {
                if (!completed[0]) {
                    try {
                        completed.wait(3000);
                    } catch (InterruptedException e) {
                        Log.e(TAG, "等待悬赏任务更新结果被中断", e);
                    }
                }
            }
            
            return success[0];
        } catch (Exception e) {
            Log.e(TAG, "更新悬赏任务失败", e);
            return false;
        }
    }

    /**
     * 删除悬赏任务 - 通过API
     */
    public static boolean deleteRewardTask(int taskId) {
        Log.d(TAG, "删除悬赏任务: " + taskId);
        
        try {
            // 此方法需要上下文，但没有直接传入，需要想办法获取应用上下文
            Context context = AppGlobalContext.getAppContext();
            if (context == null) {
                Log.e(TAG, "删除悬赏任务失败: 上下文为空");
                return false;
            }
            
            String token = getAuthToken(context);
            if (token == null || token.isEmpty()) {
                Log.e(TAG, "删除悬赏任务失败: 授权令牌为空");
                return false;
            }
            
            // 获取API实例并发起异步请求
            UserApi api = getAuthenticatedUserApi(context);
            final boolean[] success = {false}; // 用数组存储结果，以便在回调中修改
            final boolean[] completed = {false}; // 用于标记请求是否完成
            
            // 假设UserApi中有删除悬赏任务的方法
            Call<CommonResponse> call = api.deleteAdvertisement("Bearer " + token, taskId);
            
            call.enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        success[0] = response.body().isSuccess();
            } else {
                        Log.e(TAG, "删除悬赏任务API调用失败: " + response.code());
                    }
                    completed[0] = true;
                    synchronized (completed) {
                        completed.notify(); // 通知等待线程
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    Log.e(TAG, "删除悬赏任务网络请求失败", t);
                    completed[0] = true;
                    synchronized (completed) {
                        completed.notify(); // 通知等待线程
                    }
                }
            });
            
            // 等待一段时间，最多3秒
            synchronized (completed) {
                if (!completed[0]) {
                    try {
                        completed.wait(3000);
                    } catch (InterruptedException e) {
                        Log.e(TAG, "等待删除悬赏任务结果被中断", e);
                    }
                }
            }
            
            return success[0];
        } catch (Exception e) {
            Log.e(TAG, "删除悬赏任务失败", e);
            return false;
        }
    }

    /**
     * 更新任务状态 - 通过API
     */
    public static boolean updateTask(Task task) {
        Log.d(TAG, "更新任务: " + task.getId() + ", " + task.getTitle() + ", 状态: " + task.getStatus());
        
        try {
            // 获取当前上下文，因为是静态方法，需要在调用时传入上下文
            Context context = task.getContext();
            if (context == null) {
                Log.e(TAG, "更新任务失败: 上下文为空");
                return false;
            }
            
            String token = getAuthToken(context);
            if (token == null || token.isEmpty()) {
                Log.e(TAG, "更新任务失败: 授权令牌为空");
        return false;
    }
    
            // 准备请求数据
            Map<String, Object> updateData = new HashMap<>();
            updateData.put("taskId", task.getId());
            updateData.put("status", task.getStatus());
            updateData.put("reviewTime", task.getReviewTime());
            if (task.getRejectReason() != null && !task.getRejectReason().isEmpty()) {
                updateData.put("rejectReason", task.getRejectReason());
            }
            
            // 获取API实例并发起异步请求
            UserApi api = getAuthenticatedUserApi(context);
            final boolean[] success = {false}; // 用数组存储结果，以便在回调中修改
            final boolean[] completed = {false}; // 用于标记请求是否完成
            
            api.updateTask("Bearer " + token, task.getId(), updateData).enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        success[0] = response.body().isSuccess();
                    } else {
                        Log.e(TAG, "更新任务API调用失败: " + response.code());
                    }
                    completed[0] = true;
                    synchronized (completed) {
                        completed.notify(); // 通知等待线程
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    Log.e(TAG, "更新任务网络请求失败", t);
                    completed[0] = true;
                    synchronized (completed) {
                        completed.notify(); // 通知等待线程
                    }
                }
            });
            
            // 等待一段时间，最多3秒
            synchronized (completed) {
                if (!completed[0]) {
                    try {
                        completed.wait(3000);
                    } catch (InterruptedException e) {
                        Log.e(TAG, "等待任务更新结果被中断", e);
                    }
                }
            }
            
            return success[0];
        } catch (Exception e) {
            Log.e(TAG, "更新任务失败", e);
            return false;
        }
    }

    /**
     * 更新用户头像
     * @param username 用户名
     * @param avatarUrl 头像URL
     * @return 是否更新成功
     */
    public static boolean updateUserAvatar(String username, String avatarUrl) {
        Log.d(TAG, "更新用户头像: " + username);
        
        try {
            // 获取应用上下文
            Context context = AppGlobalContext.getAppContext();
            if (context == null) {
                Log.e(TAG, "更新用户头像失败: 上下文为空");
                return false;
            }
            
            String token = getAuthToken(context);
            if (token == null || token.isEmpty()) {
                Log.e(TAG, "更新用户头像失败: 授权令牌为空");
                return false;
            }
            
            // 准备请求数据
            Map<String, Object> updateData = new HashMap<>();
            updateData.put("username", username);
            updateData.put("avatarUrl", avatarUrl);
            
            // 获取API实例并发起异步请求
            UserApi api = getAuthenticatedUserApi(context);
            final boolean[] success = {false}; // 用数组存储结果，以便在回调中修改
            final boolean[] completed = {false}; // 用于标记请求是否完成
            
            api.updateUserAvatar("Bearer " + token, updateData).enqueue(new Callback<CommonResponse>() {
                @Override
                public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        success[0] = response.body().isSuccess();
                        Log.d(TAG, "更新用户头像成功: " + response.body().getMessage());
                    } else {
                        Log.e(TAG, "更新用户头像API调用失败: " + response.code());
                    }
                    completed[0] = true;
                    synchronized (completed) {
                        completed.notify(); // 通知等待线程
                    }
                }

                @Override
                public void onFailure(Call<CommonResponse> call, Throwable t) {
                    Log.e(TAG, "更新用户头像网络请求失败", t);
                    completed[0] = true;
                    synchronized (completed) {
                        completed.notify(); // 通知等待线程
                    }
                }
            });
            
            // 等待一段时间，最多3秒
            synchronized (completed) {
                if (!completed[0]) {
                    try {
                        completed.wait(3000);
                    } catch (InterruptedException e) {
                        Log.e(TAG, "等待更新用户头像结果被中断", e);
                    }
                }
            }
            
            return success[0];
        } catch (Exception e) {
            Log.e(TAG, "更新用户头像失败", e);
            return false;
        }
    }
}